<template>
  <div class="register-container">
    <div class="register-box">
      <div class="logo-container">
        <div class="logo">注册</div>
      </div>
      <h2 class="title">创建您的账户</h2>
      <p class="subtitle">填写以下信息完成注册</p>
      <el-form id="registerForm" autocomplete="on" @submit.prevent="handleRegister">
        <el-form-item :error="errors.username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            autocomplete="username"
            name="username"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item :error="errors.password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            autocomplete="new-password"
            name="password"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item :error="errors.confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            autocomplete="new-password"
            name="confirmPassword"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item :error="errors.email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱"
            autocomplete="email"
            name="email"
            :prefix-icon="Message"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="register-btn" :loading="loading" @click="handleRegister">
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
        <div class="login-link" @click="goToLogin">已有账号？去登录</div>
        <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon class="error-alert" />
      </el-form>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { register } from '../api/user';
  import { saveUserInput, getUserInput } from '../utils/storage';
  import { User, Lock, Message } from '@element-plus/icons-vue';

  const router = useRouter();
  const loading = ref(false);
  const errorMessage = ref('');

  // 添加错误信息对象，用于存储每个字段的错误信息
  const errors = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
  });

  // 注册表单数据
  const registerForm = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
  });

  // 组件挂载时，从本地存储获取用户名
  onMounted(() => {
    // 获取之前保存的用户名
    registerForm.username = getUserInput('username');
  });

  // 实时监听密码和确认密码的变化，检查是否一致
  watch([() => registerForm.password, () => registerForm.confirmPassword], ([newPassword, newConfirmPassword]) => {
    // 只有当两个字段都有值时才进行比较
    if (newPassword && newConfirmPassword) {
      if (newPassword !== newConfirmPassword) {
        errors.confirmPassword = '两次输入的密码不一致';
      } else {
        errors.confirmPassword = '';
      }
    } else {
      // 如果有一个字段为空，清除错误提示
      errors.confirmPassword = '';
    }
  });

  // 处理注册
  const handleRegister = async () => {
    // 重置所有错误信息
    Object.keys(errors).forEach((key) => (errors[key] = ''));
    errorMessage.value = '';

    // 表单验证 - 必填项检查
    let hasError = false;

    if (!registerForm.username) {
      errors.username = '用户名不能为空';
      hasError = true;
    } else if (!/^[a-zA-Z0-9_]{3,20}$/.test(registerForm.username)) {
      errors.username = '用户名只能包含字母、数字和下划线，长度3-20位';
      hasError = true;
    }

    if (!registerForm.password) {
      errors.password = '密码不能为空';
      hasError = true;
    } else if (registerForm.password.length < 6 || registerForm.password.length > 20) {
      errors.password = '密码长度必须在6-20位之间';
      hasError = true;
    }

    if (!registerForm.confirmPassword) {
      errors.confirmPassword = '请确认密码';
      hasError = true;
    } else if (registerForm.password !== registerForm.confirmPassword) {
      errors.confirmPassword = '两次输入的密码不一致';
      hasError = true;
    }

    if (!registerForm.email) {
      errors.email = '邮箱不能为空';
      hasError = true;
    } else if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(registerForm.email)) {
      errors.email = '请输入有效的邮箱地址';
      hasError = true;
    }

    if (hasError) {
      return;
    }

    // 保存用户名到本地存储（不保存密码）
    saveUserInput('username', registerForm.username);

    try {
      loading.value = true;
      errorMessage.value = '';

      // 构建注册数据，与Python测试代码一致
      const registerData = {
        username: registerForm.username,
        password: registerForm.password,
        email: registerForm.email, // 如果没有提供邮箱，使用默认值
      };

      const res = await register(registerData);

      if (res.message === '注册成功') {
        // 注册成功，跳转到登录页
        router.push('/login');
      } else {
        errorMessage.value = res.detail || '注册失败';
      }
    } catch (error) {
      console.error('注册错误:', error);
      errorMessage.value = '注册失败，请稍后重试';
    } finally {
      loading.value = false;
    }
  };

  // 跳转到登录页
  const goToLogin = () => {
    router.push('/login');
  };
</script>

<style lang="less" scoped>
  .register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);

    .register-box {
      width: 420px;
      padding: 35px;
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &:hover {
        box-shadow: 0 16px 32px rgba(0, 0, 0, 0.18);
      }

      .logo-container {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;

        .logo {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          background: var(--el-color-primary);
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          font-weight: bold;
          box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
        }
      }

      .title {
        text-align: center;
        margin-bottom: 8px;
        color: #333;
        font-size: 24px;
        font-weight: 600;
      }

      .subtitle {
        text-align: center;
        color: #909399;
        margin-bottom: 25px;
        font-size: 14px;
      }

      :deep(.el-form-item) {
        margin-bottom: 22px;
      }

      :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 1px #e0e3e9 inset;
        border-radius: 8px;
        padding: 0 15px;
        transition: all 0.3s ease;
        height: 45px;

        &.is-focus {
          box-shadow:
            0 0 0 1px var(--el-color-primary) inset,
            0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
        }

        &:hover {
          box-shadow:
            0 0 0 1px var(--el-color-primary) inset,
            0 0 0 3px rgba(var(--el-color-primary-rgb), 0.05);
        }
      }

      :deep(.el-input__inner) {
        height: 45px;
      }

      :deep(.el-form-item__error) {
        padding-top: 4px;
        font-size: 12px;
      }

      .register-btn {
        width: 100%;
        height: 45px;
        font-size: 16px;
        font-weight: 500;
        border-radius: 8px;
        margin-top: 10px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
        }
      }

      .login-link {
        text-align: center;
        color: var(--el-color-primary);
        cursor: pointer;
        margin: 20px 0;
        font-size: 14px;
        transition: all 0.2s ease;

        &:hover {
          color: var(--el-color-primary-dark-2);
          transform: translateY(-1px);
        }
      }

      .error-alert {
        margin-top: 15px;
        border-radius: 8px;
      }
    }
  }

  @media (max-width: 480px) {
    .register-box {
      width: 90%;
      padding: 25px;
    }
  }
</style>
